package com.mxw.wechatai.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mxw.wechatai.entity.UserInfo;
import com.mxw.wechatai.mapper.UserInfoMapper;
import com.mxw.wechatai.service.DeepSeekService;
import com.mxw.wechatai.service.WebCrawlerService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
public class IndexController {
    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    DeepSeekService deepSeekService;

    @Autowired
    WebCrawlerService webCrawlerService;

    @Autowired
    UserInfoMapper userInfoMapper;

    private static final String PROMPT_TEMPLATE = "你是专业的文案工作者。你根据文案的题材性质进行重写。我是一个公众号博主，帮我写一篇关于的公众号文章，需要符合该平台写作风格。" +
            "改写要求：文案必须健康正能量，保持原文的核心观点和主题，改变语句结构和措辞，不要抄袭原文，增加细节描写，使语言更丰富，调整结构增强逻辑性，改变文体使语言更生动流畅。段落要求在5个自然段左右，总字数不超过1000字。给出一个标题。风格是 %s。不要出现改写说明。" +
            "原文：%s";

    @GetMapping("/")
    public String indexPage() {
        return "index";
    }

    @PostMapping("/articleCreate")
    @ResponseBody
    public Map<String, Object> articleCreate(@RequestParam(required = false) String url,
                                             @RequestParam(required = false) String text,
                                             @RequestParam(required = false) String keywords,
                                             @RequestParam(required = false) String style,
                                             HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        // 检查登录状态
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
        if (userInfo == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }

        // 检查使用次数
        if (userInfo.getCount() <= 0) {
            result.put("success", false);
            result.put("message", "你当前的试用次数已用完，请立即永久激活使用");
            return result;
        }

        try {
            String originalText;
            // 判断是URL输入还是文本输入
            if (text != null && !text.trim().isEmpty()) {
                originalText = text;
            } else if (url != null && !url.trim().isEmpty()) {
                // 获取网页内容
                originalText = webCrawlerService.getWebContent(url);
                if (originalText == null || originalText.trim().isEmpty()) {
                    result.put("success", false);
                    result.put("message", "无法获取网页内容，请检查URL是否正确");
                    return result;
                }
            } else {
                result.put("success", false);
                result.put("message", "请输入URL或文章内容");
                return result;
            }

            // 根据选择的风格调整提示词
            String stylePrompt = "";
            if (style != null) {
                switch (style) {
                    case "professional":
                        stylePrompt = "使用专业严谨的语言风格，";
                        break;
                    case "casual":
                        stylePrompt = "使用轻松活泼的语言风格，";
                        break;
                    case "story":
                        stylePrompt = "使用故事叙述的语言风格，";
                        break;
                }
            }

            // 构建完整的提示词
            String prompt = String.format(PROMPT_TEMPLATE, stylePrompt, originalText);
            if (keywords != null && !keywords.trim().isEmpty()) {
                prompt += "\n\n请确保文章包含以下关键词：" + keywords;
            }

            // 调用AI服务生成文章
            String response = deepSeekService.sendRequest(prompt);
            if (response == null || response.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "AI生成文章失败，请稍后重试");
                return result;
            }

            // 提取标题和格式化内容
            String title = "";
            if (response.contains("**")) {
                int startIndex = response.indexOf("**");
                int endIndex = response.indexOf("**", startIndex + 2);
                if (startIndex != -1 && endIndex != -1) {
                    title = response.substring(startIndex + 2, endIndex).trim();
                }
                title = title.replace("标题：", "");
            }

            // 处理AI返回的内容，确保格式正确
            String formattedContent = formatArticleContent(response);

            // 减少用户使用次数
            userInfo.setCount(userInfo.getCount() - 1);
            userInfoMapper.updateById(userInfo);

            result.put("success", true);
            result.put("title", title);
            result.put("content", formattedContent);
            result.put("message", "文章生成成功");

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "文章生成失败：" + e.getMessage());
        }

        return result;
    }



    @PostMapping("/createDraft")
    @ResponseBody
    public Map<String, Object> createDraft(
            @RequestParam(required = true) String data,
            @RequestParam(required = false) MultipartFile coverImage,
            HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");

        if (userInfo == null) {
            logger.warn("用户未登录，session: {}", session.getId());
            result.put("success", false);
            result.put("message", "请先登录");
            return result;
        }

        // 检查用户是否配置了公众号信息
        if (userInfo.getAppid() == null || userInfo.getAppid().trim().isEmpty() ||
            userInfo.getSecret() == null || userInfo.getSecret().trim().isEmpty()) {
            logger.warn("用户 {} 未配置公众号信息", userInfo.getUserName());
            result.put("success", false);
            result.put("message", "请先在设置中配置您的公众号信息。查看帮助文档了解如何获取公众号信息。");
            return result;
        }

        try {
            logger.info("{} 开始创建草稿", userInfo.getUserName());
            
            // 解析JSON数据
            JSONObject jsonData = JSON.parseObject(data);
            String text = jsonData.getString("text");
            String title = jsonData.getString("title");
            logger.debug("{}  草稿标题: {}",userInfo.getUserName(), title);


            // 配置微信公众号信息
            WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
            config.setAppId(userInfo.getAppid());
            config.setSecret(userInfo.getSecret());

            // 创建微信服务实例
            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(config);

            // 处理封面图片
            String thumbMediaId;
            if (coverImage == null || coverImage.isEmpty()) {
                logger.warn("{} 未上传封面图片",userInfo.getUserName());
                result.put("success", false);
                result.put("message", "请上传封面图片");
                return result;
            }
            
            logger.info("{} 开始处理封面图片: {}", userInfo.getUserName(),coverImage.getOriginalFilename());
            // 创建一个临时文件来保存上传的图片
            File tempFile = File.createTempFile("upload_", "_" + coverImage.getOriginalFilename());
            coverImage.transferTo(tempFile);
            logger.debug("{} 临时文件创建成功: {}", userInfo.getUserName(),tempFile.getAbsolutePath());

            WxMpMaterial material = new WxMpMaterial();
            material.setFile(tempFile);
            material.setName(coverImage.getOriginalFilename());
            
            try {
                logger.info("{} 开始上传封面图片到微信服务器",userInfo.getUserName());
                WxMpMaterialUploadResult uploadResult = wxMpService.getMaterialService().materialFileUpload(
                        WxConsts.MediaFileType.IMAGE,
                        material
                );
                thumbMediaId = uploadResult.getMediaId();
                logger.info("{} 封面图片上传成功，media_id: {}", userInfo.getUserName(),thumbMediaId);
            } catch (Exception e) {
                logger.error("{} 封面图片上传失败",userInfo.getUserName(), e);
                result.put("success", false);
                result.put("message", "封面图片上传失败: " + e.getMessage());
                return result;
            } finally {
                // 删除临时文件
                if (tempFile.delete()) {
                    logger.debug("{} 临时文件删除成功",userInfo.getUserName());
                } else {
                    logger.warn("{} 临时文件删除失败: {}", userInfo.getUserName(), tempFile.getAbsolutePath());
                }
            }

            // 创建草稿文章列表
            List<Map<String, Object>> articles = new ArrayList<>();
            Map<String, Object> article = new HashMap<>();
            article.put("title", title);
            article.put("author", userInfo.getUserName());
            article.put("digest", title);
            article.put("content", text);
            article.put("thumb_media_id", thumbMediaId);
            article.put("show_cover_pic", 1);
            article.put("need_open_comment", 1);
            article.put("only_fans_can_comment", 0);
            article.put("need_open_reprint", 0);
            articles.add(article);

            // 创建草稿
            Map<String, Object> draftData = new HashMap<>();
            draftData.put("articles", articles);
            draftData.put("need_open_comment", 1);
            draftData.put("only_fans_can_comment", 0);
            draftData.put("need_open_reprint", 0);

            logger.info("开始创建草稿");
            // 调用接口创建草稿
            String response = wxMpService.post("https://api.weixin.qq.com/cgi-bin/draft/add?need_open_comment=1&only_fans_can_comment=0&need_open_reprint=0",
                    JSON.toJSONString(draftData));

            JSONObject jsonResult = JSON.parseObject(response);
            if (jsonResult != null) {
                logger.info("{} 草稿创建成功",userInfo.getUserName());
                result.put("success", true);
                result.put("message", "群发成功");
            } else {
                logger.error("{} 草稿创建失败，返回结果为空",userInfo.getUserName());
                result.put("success", false);
                result.put("message", "群发失败：未知错误");
            }

            // 创建微信服务实例
            wxMpService.setWxMpConfigStorage(config);

            // 获取草稿列表
            String draftListResult = wxMpService.post("https://api.weixin.qq.com/cgi-bin/draft/batchget", "{\"offset\":0,\"count\":20,\"no_content\":0}");
            if (draftListResult == null) {
                logger.error("{} 获取草稿列表失败，返回结果为空",userInfo.getUserName());
                throw new RuntimeException("获取草稿列表失败，返回结果为空");
            }

            JSONObject jsonResult2 = JSON.parseObject(draftListResult);
            if (jsonResult2 == null) {
                logger.error("{} 解析草稿列表返回结果失败",userInfo.getUserName());
                throw new RuntimeException("解析返回结果失败");
            }

            Integer errcode = Optional.ofNullable(jsonResult2.getInteger("errcode")).orElse(0);
            if (errcode != 0) {
                logger.error("{} 获取草稿列表失败: {}", userInfo.getUserName(),jsonResult2.getString("errmsg"));
                throw new RuntimeException("获取草稿列表失败: " + jsonResult2.getString("errmsg"));
            }

            // 获取最新的草稿media_id
            JSONArray items = jsonResult2.getJSONArray("item");
            if (items == null || items.isEmpty()) {
                logger.error("{} 没有找到草稿",userInfo.getUserName());
                throw new RuntimeException("没有找到草稿");
            }

            String mediaId = items.getJSONObject(0).getString("media_id");
            logger.info("{} 获取到最新草稿media_id: {}", userInfo.getUserName(),mediaId);

            // 群发文章
            Map<String, Object> massSendData = new HashMap<>();
            massSendData.put("filter", new HashMap<String, Object>() {{
                put("is_to_all", true);
            }});

            massSendData.put("mpnews", new HashMap<String, Object>() {{
                put("media_id", mediaId);
            }});

            massSendData.put("msgtype", "mpnews");
            massSendData.put("send_ignore_reprint", 0); // 0表示不忽略原创声明

            logger.info("{} 开始群发文章",userInfo.getUserName());
            String massSendResult = wxMpService.post("https://api.weixin.qq.com/cgi-bin/message/mass/sendall", JSON.toJSONString(massSendData));

            if (massSendResult == null) {
                logger.error("群发文章失败，返回结果为空");
                throw new RuntimeException("群发文章失败，返回结果为空");
            }

            JSONObject massSendJsonResult = JSON.parseObject(massSendResult);

            if (massSendJsonResult == null) {
                logger.error("{} 解析群发返回结果失败",userInfo.getUserName());
                throw new RuntimeException("解析群发返回结果失败");
            }

            errcode = Optional.ofNullable(massSendJsonResult.getInteger("errcode")).orElse(0);
            if (errcode == 0) {
                String msgId = massSendJsonResult.getString("msg_id");
                logger.info("{} 群发文章成功，msg_id: {}",userInfo.getUserName(), msgId);
                result.put("success", true);
                result.put("message", "群发成功");
            } else {
                if (errcode == 45028) {
                    logger.warn("{} 群发次数已用光",userInfo.getUserName());
                    result.put("success", false);
                    result.put("message", "群发失败：群发次数已用光。");
                } else {
                    logger.error("{} 群发失败: {}", userInfo.getUserName(),massSendJsonResult.getString("errmsg"));
                    result.put("success", false);
                    result.put("message", "群发失败：" + massSendJsonResult.getString("errmsg"));
                }
            }
        } catch (Exception e) {
            String message = Optional.ofNullable(e.getMessage()).orElse("");
            if (message.contains("48001")) {
                logger.warn("{} 公众号没有群发接口权限",userInfo.getUserName());
                result.put("success", false);
                result.put("message", "群发失败：你的公众号没有群发接口权限。已存放在草稿箱。");
            } else if (message.contains("45028")) {
                logger.warn("{} 群发次数已用光",userInfo.getUserName());
                result.put("success", false);
                result.put("message", "群发失败：群发次数已用光。");
            } else if (message.contains("40164")){
                result.put("success", false);
                result.put("message", "群发失败：请将 8.213.231.74 设置白名单。具体请看帮助文档。");
            }else {
                logger.error("{} 群发失败", userInfo.getUserName(),e);
                result.put("success", false);
                result.put("message", "群发失败：" + e.getMessage());
            }
        }
        return result;
    }

    // 请求体对象
    public static class DraftRequest {
        private String text;  // HTML格式的文章内容
        private String title; // 文章标题
        private String coverImage; // base64格式的图片数据

        // Getters and Setters
        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getCoverImage() {
            return coverImage;
        }

        public void setCoverImage(String coverImage) {
            this.coverImage = coverImage;
        }
    }

    /**
     * 格式化文案内容为微信公众号推文格式
     *
     * @param content 原始文案内容
     * @return 格式化后的文案内容
     */
    private String formatArticleContent(String content) {
        // 提取标题（仅用于返回，不显示在正文中）
        String title = "";
        if (content.contains("**")) {
            int startIndex = content.indexOf("**");
            int endIndex = content.indexOf("**", startIndex + 2);
            if (startIndex != -1 && endIndex != -1) {
                title = content.substring(startIndex + 2, endIndex).trim();
                // 移除标题部分
                content = content.substring(endIndex + 2).trim();
            }
        }

        // 去除段落标记（如"**第一段：推荐开场**"）
        content = content.replaceAll("\\*\\*.*?\\*\\*\\s*", "");
        content = content.replaceAll("#", "");

        // 分割段落
        String[] paragraphs = content.split("\n\n");
        StringBuilder formattedContent = new StringBuilder();

        // 添加文章容器样式
        formattedContent.append("<div style='max-width: 100%; margin: 0 auto; padding: 0 15px; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif;'>\n");

        // 处理每个段落
        for (int i = 0; i < paragraphs.length; i++) {
            String paragraph = paragraphs[i].trim();
            if (paragraph.isEmpty()) continue;

            // 检查是否是引用段落（以">"开头）
            if (paragraph.startsWith(">")) {
                paragraph = paragraph.substring(1).trim();
                formattedContent.append("<blockquote style='margin: 20px 0; padding: 15px; background-color: #f8f8f8; border-left: 4px solid #ddd; color: #666;'>")
                        .append(paragraph)
                        .append("</blockquote>\n\n");
            }
            // 检查是否是强调段落（以"*"开头和结尾）
            else if (paragraph.startsWith("*") && paragraph.endsWith("*")) {
                paragraph = paragraph.substring(1, paragraph.length() - 1).trim();
                formattedContent.append("<p style='font-size: 16px; line-height: 1.8; color: #333; margin: 20px 0; text-align: center; font-weight: bold;'>")
                        .append(paragraph)
                        .append("</p>\n\n");
            }
            // 普通段落
            else {
                // 为第一个段落添加特殊样式
                if (i == 0) {
                    formattedContent.append("<p style='font-size: 16px; line-height: 1.8; color: #333; margin: 20px 0; text-align: justify; font-weight: 500;'>")
                            .append(paragraph)
                            .append("</p>\n\n");
                } else {
                    formattedContent.append("<p style='font-size: 16px; line-height: 1.8; color: #333; margin: 20px 0; text-align: justify;'>")
                            .append(paragraph)
                            .append("</p>\n\n");
                }
            }

            // 在段落之间添加优雅的分割线（除了最后一个段落）
            if (i < paragraphs.length - 1) {
                formattedContent.append("<section style='margin: 12px 0; text-align: center;'>")
                        .append("<section style='display: inline-block; width: 120px; height: 1px; background: linear-gradient(to right, transparent, rgba(158, 158, 158, 0.3), rgba(158, 158, 158, 0.6), rgba(158, 158, 158, 0.3), transparent); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);'></section>")
                        .append("</section>");
            }
        }

        // 关闭文章容器
        formattedContent.append("</div>");

        return formattedContent.toString();
    }

} 